package com.imdroid.carac.services;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.activities.HomeActivity;
import com.imdroid.carac.activities.SecurityHomeActivity;
import com.imdroid.carac.activities.TeamMapActivity;
import com.imdroid.carac.model.Destination;
import com.imdroid.carac.model.Team;
import com.imdroid.carac.model.TeamMember;
import com.imdroid.carac.process.PlaySoundProcess;

/**
 * The action handler of notification
 * 
 */
public class NotificationHandler extends Handler {
	private static final String TAG = "NotificationHandler";

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.Handler#handleMessage(android.os.Message)
	 */
	public void handleMessage(android.os.Message msg) {
		switch (msg.what) {
		case NotificationService.CONNECTED:
			Toast.makeText(IMDroid.getContext(),
					IMDroid.getContext().getString(R.string.server_connected),
					Toast.LENGTH_SHORT).show();
			break;
		case NotificationService.CONNECT_FAIL:
			Toast.makeText(
					IMDroid.getContext(),
					IMDroid.getContext()
							.getString(R.string.server_connect_fail),
					Toast.LENGTH_SHORT).show();
			break;
		case NotificationService.RECEIVED:
			// 处理通知事件
			Log.d(TAG, msg.obj + "");
			handleNotification("" + msg.obj);
			break;
		case NotificationService.DISCONNECTED:
			Toast.makeText(IMDroid.getContext(),
					IMDroid.getContext().getString(R.string.call_disconnect),
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	/**
	 * handle the notification message
	 * 
	 * @param message
	 *            the message
	 */
	private void handleNotification(String message) {
		
		String text[] = message.split("&&");

		// 判断消息格式是否正确
		if (text == null || text.length < 2 || text[0] == null
				|| "".equals(text[0])) {
			return;
		}
		int n = Integer.parseInt(text[0]);
		Log.d(TAG, "RUN --------" + n);
		switch (n) {
		case NotificationMessage.NOTIFICATION_PING:
			break;
		case NotificationMessage.NOTIFICATION_CALL:
			Log.d(TAG, "RUN --------call");
			// 播出对讲的声音文件
			speak(text[1].trim());
			break;
		case NotificationMessage.NOTIFICATION_LOCATION:
			// 保存队友最近一次GPS位置
			// IMDroid.saveMemberLastLocation(message);
			// 更新队友GPS位置
			System.out.println("message:"+message+";; text[7]:"+ text[7]);
			Float userId = Float.parseFloat(text[1]);
			float longitude = Float.parseFloat(text[2]);
			float latitude = Float.parseFloat(text[3]);
			float speed = Float.parseFloat(text[4]);
			String userName = text[5];
			float direction = Float.parseFloat(text[6]);
			String deviceType = text[7];
			refreshTeam(userId.intValue(), longitude, latitude, speed,
					userName, direction, deviceType);
			break;
		// case NotificationMessage.NOTIFICATION_ADDTOTEAM:
		// 加入队伍邀请
		// String[] items = text[1].split(";");
		// addToTeam(items[0], items[1], items[2]);
		// break;
		case NotificationMessage.NOTIFICATION_CONFIRM:
			joinTeam();
			break;
		case NotificationMessage.NOTIFICATION_EXIT:
			// 用户退出当前队伍
			exitTeam();
			break;
		// case NotificationMessage.NOTIFICATION_TEAM_CANCEL:
		// 解散队伍
		// cancelTeam();
		// break;
		case NotificationMessage.NOTIFICATION_TEAMDESTINATION:
			// 接受到目的地
			if (text.length >= 5) {
				String name = text[1];
				float dest_lat = Float.parseFloat(text[2]);
				float dest_lon = Float.parseFloat(text[3]);
				boolean routeSearch = text[4].trim().equals("1");
				recevieTeamDestination(name, dest_lat, dest_lon, routeSearch);
			}
			break;
		case NotificationMessage.NOTIFICATION_Destination:
			if (text.length >= 4) {
				String name = text[1];
				float dest_lat = Float.parseFloat(text[3]);
				float dest_lon = Float.parseFloat(text[2]);
				recevieDestination(name, dest_lat, dest_lon);
			}
			break;
		case NotificationMessage.NOTIFICATION_TakePicture:
			try {
				String feedBackNumber = text[1];
				takingPicture(feedBackNumber);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 播出语音信息
	 */
	private void speak(String soundFile) {
		PlaySoundProcess.speak2(soundFile);
	}

	/**
	 * Other team member confirm to join
	 */
	private void joinTeam() {
		// 播放声音
		PlaySoundProcess.playSound(PlaySoundProcess.confirm);
		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_REFRESH);
		}
	}

	/**
	 * 退出队伍
	 */
	private void exitTeam() {
		// 播放声音
		PlaySoundProcess.playSound(PlaySoundProcess.exit);

		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_REFRESH);
		}
	}

	/**
	 * Refresh the user's location
	 * 
	 * @param userId
	 *            the target user id
	 * @param longitude
	 *            the user's location - longitude
	 * @param latitude
	 *            the user's location - latitude
	 * @param name
	 *            the user's name
	 */
	private void refreshTeam(int userId, float longitude, float latitude,
			float speed, String userName, float direction, String deviceType) {
		Team team = Team.getCurrentTeam();
		if (team == null || team.getMembers() == null)
			return;
		// 更改缓存中的对象
		TeamMember member = team.getMembers().get(userId);
		if (member != null) {
			Log.d(TAG, "--" + member.getDisplayName() + " " + latitude + " "
					+ longitude);
			member.setLat(latitude);
			member.setLon(longitude);
			member.setSpeed(speed);
			member.setDirect(direction);
			member.setDeviceType(deviceType);
		}

		// 刷新队员列表
		TeamMapActivity instance = TeamMapActivity.instance;
		if (instance != null && instance.isActive()) {
			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_UPDATE);
		}
		return;
	}

	/**
	 * Receive the desiniation
	 * 
	 * @param destination
	 *            the name of destination
	 * @param lat
	 *            latitude of the destination
	 * @param lon
	 *            longitude of the destination
	 * @param routeSearch
	 *            if need the search the route when setting the desination
	 */
	private void recevieTeamDestination(String destination, float lat,
			float lon, boolean routeSearch) {
		if (Team.getCurrentTeam() != null) {
			Team.getCurrentTeam().setDestinationName(destination);
			Team.getCurrentTeam().setDestinationLat(lat);
			Team.getCurrentTeam().setDestinationLon(lon);
			Team.getCurrentTeam().setSearchRoute(routeSearch);

			PlaySoundProcess.playSound(PlaySoundProcess.confirm);
			TeamMapActivity instance = TeamMapActivity.instance;

			instance.getHandler().sendEmptyMessage(
					TeamMapActivity.EVENT_TEAM_RECEIVE_LOCATION);

			Toast.makeText(
					instance,
					IMDroid.getContext().getResources()
							.getString(R.string.team_map_destination),
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Receive the desiniation
	 * 
	 * @param destination
	 *            the name of destination
	 * @param lat
	 *            latitude of the destination
	 * @param lon
	 *            longitude of the destination
	 */
	private void recevieDestination(String destination, float lat, float lon) {
		HomeActivity homeActivity = HomeActivity.getInstance();
		homeActivity.refreshNavigationIcon();
		Destination d = new Destination(destination, lat, lon);
		IMDroid.setDestination(d);
		String s = IMDroid.getContext().getString(R.string.loc_new_address);
		s = s.replace("%1%", d.getAddress());
		Toast.makeText(IMDroid.getContext(), s, Toast.LENGTH_SHORT).show();
	}

	/**
	 * Take the pictures
	 * 
	 * @throws Exception
	 */
	private void takingPicture(String feedBackNumber) throws Exception {
		SecurityHomeActivity isntance = SecurityHomeActivity.instance;
		Log.d(TAG, feedBackNumber);
		// 如果已经打开-已在安防状态
		if (isntance != null && isntance.running) {
			Message message = new Message();
			message.what = SecurityHomeActivity.MESSAGE_TAKE_PICTURE;
			message.obj = feedBackNumber;
			isntance.getHandler().sendEmptyMessage(
					SecurityHomeActivity.MESSAGE_TAKE_PICTURE);
		} else {
			//如果要新开窗口
			Activity context = HomeActivity.getInstance();
			Intent intent = new Intent(IMDroid.getContext(),
					SecurityHomeActivity.class);
			intent.putExtra("action", "TakingPicture");
			intent.putExtra("feedBackNumber", feedBackNumber);
			context.startActivityForResult(intent, 1);
		}
	}

	/**
	 * The message of notification
	 * 
	 */
	private class NotificationMessage {
		/**
		 * The type of notification - empty information to maintain the
		 * connection
		 */
		public static final int NOTIFICATION_PING = 101;
		/**
		 * The type of notification - call
		 */
		public static final int NOTIFICATION_CALL = 102;
		/**
		 * The type of notification - GPS location
		 */
		public static final int NOTIFICATION_LOCATION = 103;
		/**
		 * The type of notification - GPS location
		 */
		// public static final int NOTIFICATION_ADDTOTEAM = 104;

		/**
		 * Team cancel(or exit the team)
		 */
		// public static final int NOTIFICATION_TEAM_CANCEL = 105;

		/**
		 * The type of notification - confirm add.
		 */
		public static final int NOTIFICATION_CONFIRM = 106;

		/**
		 * The type of notification - user exit the current team
		 */
		public static final int NOTIFICATION_EXIT = 108;
		/**
		 * The type of notification - exit from the team
		 */
		public static final int NOTIFICATION_TEAMDESTINATION = 110;
		/**
		 * The type of notification - receive the destination
		 */
		public static final int NOTIFICATION_Destination = 109;
		/**
		 * The type of notification - Take the pictures
		 */
		public static final int NOTIFICATION_TakePicture = 120;
	}
}
